from app.extensions import SessionLocal
from app.models.Clas import Clas
from app.models.Student import Student


class ClasRepository():
    def __init__(self, db: SessionLocal):
        self.db = db

    def get_by_keyword(self, keyword):
        try:
            data = self.db.query(Clas).filter(Clas.name.like(f'%{keyword}%')).all()
            return data
        except Exception as e:
            print(f'查询错误: {e}')
            return []

    def get_clas_by_name(self, name):
        try:
            data = self.db.query(Clas).filter(Clas.name == name).one()
            return data
        except:
            return None

    def get_clas_by_id(self, id):
        try:
            data = self.db.query(Clas).filter(Clas.id == id).one()
            return data
        except:
            return None

    def update_clas(self, id, name):
        try:
            clas = self.get_clas_by_id(id)
            if not clas:
                return False
            clas.name = name
            self.db.commit()
            return True
        except:
            return False

    def add_clas(self, name):
        try:
            clas = Clas(name=name)
            self.db.add(clas)
            self.db.commit()
            return clas
        except:
            return False

    def delete_clas(self, clas_id: int) -> bool:
        try:
            # 查询班级是否存在
            clas = self.db.query(Clas).get(clas_id)
            if not clas:
                return False

            # 先删除关联的学生记录（避免外键约束冲突）
            self.db.query(Student).filter(Student.clas_id == clas_id).delete()

            # 删除班级
            self.db.delete(clas)
            self.db.commit()
            return True
        except Exception as e:
            self.db.rollback()
            print(f"Error deleting class: {e}")
            return False


if __name__ == '__main__':
    from app.extensions import get_db

    with get_db() as db:
        repo = ClasRepository(db)
        data = repo.get_by_keyword("")
        for d in data:
            print(d)